package com.it.Controller;

import com.it.Service.FlightService;
import com.it.Service.OrderService;
import com.it.pojo.Flight;
import com.it.pojo.Order;
import com.it.pojo.PageBean;
import com.it.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = "*") // 解决跨域问题，允许所有来源访问，实际中可配置具体域名
@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private FlightService flightService;

    //订单的分页查询
    @GetMapping("/order/{idNum}")
    public Result OList(@PathVariable String idNum,
                        @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer pageSize) {
        PageBean pageBean = orderService.OList(idNum, page, pageSize);
        return Result.success(pageBean);
    }

    //购买航班
    @PostMapping("/order")
    //通常情况下，List 类型的参数应该通过 @RequestBody 或 @RequestParam 注解来传递。
    //但Spring MVC 不支持在同一个方法中使用多个 @RequestBody 注解。
    public Result OAdd(@RequestBody List<Order> orders, @RequestParam List<String> idNumList) {
        for(Order order:orders){
            int tickets = flightService.getFlightById(order.getFNumber()).getTicket();
            if (idNumList.size() > tickets) {
                return Result.error("该航班余票不足，购买失败！");
            }

            for (String idNumber : idNumList) {
                List<String> orderedFNums = orderService.getFNumByIdNum(idNumber);
                List<Flight> orderedFlights = new ArrayList<>();
                for(String orderedFNum:orderedFNums){
                    orderedFlights.add(flightService.getFlightById(orderedFNum));
                }
                Flight curFlight = flightService.getFlightById(order.getFNumber());
                for (Flight orderedflight : orderedFlights) {
                    if (isSameTime(orderedflight.getDepartTime(), orderedflight.getArrivalTime(), curFlight.getDepartTime(), curFlight.getArrivalTime())) {
                        return Result.error("有乘客已经购买了该时间段的机票，购买失败！");
                    }
                }
            }
            for(String idNumber:idNumList){
                order.setIdNumber(idNumber);
                //所买航班的余票 - 1
                orderService.reduceTickets(order);
            }
        }
        for(String idNumber : idNumList) {
            //增加订单
            orderService.OAdd(orders);
        }
        return Result.success();
    }

    private boolean isSameTime(LocalDateTime departTime1, LocalDateTime arrivalTime1, LocalDateTime departTime2, LocalDateTime arrivalTime2) {
        if(departTime1.isBefore(departTime2)){
            if(departTime2.isAfter(arrivalTime1)){
                return false;
            }
            return true;
        }
        else if (departTime1.isAfter(departTime2)) {
            if(departTime1.isAfter(arrivalTime2)){
                return false;
            }
            return true;
        }
        else return true;
    }

    //退票
    @PutMapping("/order/refund")
    public Result ORefund(String oNumber){
        List<String> FNumList = orderService.getFNumByONum(oNumber);
        List<Flight> flights = new ArrayList<>();
        for(String FNum:FNumList){
            flights.add(flightService.getFlightById(FNum));
        }
        LocalDateTime departTime = flights.get(0).getDepartTime();
        LocalDateTime currTime = LocalDateTime.now();
        if(currTime.isAfter(departTime)){
            return Result.error("航班已起飞，退票失败！");
        }
        if(Duration.between(currTime, departTime).toHours() < 3){
            return Result.error("距离航班起飞已不到3小时，退票失败！");
        }
        orderService.ORefund(oNumber);
        orderService.increaseTickets(oNumber);
        return Result.success();
    }

    //改签
    @PutMapping("/order/rebook")
    public Result ORebook(String oNumber){
        List<String> FNumList = orderService.getFNumByONum(oNumber);
        List<Flight> flights = new ArrayList<>();
        for(String FNum:FNumList){
            flights.add(flightService.getFlightById(FNum));
        }
        LocalDateTime departTime = flights.get(0).getDepartTime();
        LocalDateTime currTime = LocalDateTime.now();
        if(currTime.isAfter(departTime)){
            return Result.error("航班已起飞，改签失败！");
        }
        if(Duration.between(currTime, departTime).toHours() < 3){
            return Result.error("距离航班起飞已不到3小时，改签失败！");
        }
        orderService.ORebook(oNumber);
        orderService.increaseTickets(oNumber);
        return Result.success();
    }

    //删除冗余订单信息
    @DeleteMapping("/order")
    public Result ODelete(String oNumber){
        List<Order> order = orderService.getOrderById(oNumber);
        List<String> FNumList = orderService.getFNumByONum(oNumber);
        Flight flight =flightService.getFlightById(FNumList.get(0));
        LocalDateTime arriveTime = flight.getArrivalTime();
        LocalDateTime curTime = LocalDateTime.now();
        if(order.get(0).getOStatus() == 1 && curTime.isBefore(arriveTime)){
            return Result.error("该机票还未结束使用，删除失败！");
        }
        orderService.ODelete(oNumber);
        return Result.success();
    }
}
